<template>
  <div class="publish-container">
     <el-card class="filter-card">
      <div slot="header" class="clearfix">
        <!-- 导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>{{$route.query.id ? '修改文章':'发布文章'}}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-form ref="publish-form" :model="article" label-width="60px" :rules="formRules">
        <el-form-item label="标题" prop="title">
          <el-input v-model="article.title"></el-input>
        </el-form-item>
         <el-form-item label="内容" prop="content">
          <!-- <el-input type="textarea" v-model="article.content"></el-input> -->
          <el-tiptap v-model="article.content" :extensions="extensions" lang='zh' height="500px"></el-tiptap>
        </el-form-item>
        <el-form-item label="封面">
          <el-radio-group v-model="article.cover.type">
            <el-radio :label="1">单图</el-radio>
            <el-radio :label="3">三图</el-radio>
            <el-radio :label="0">无图</el-radio>
            <el-radio :label="-1">自动</el-radio>
          </el-radio-group>
          <template v-if="article.cover.type>0">
          <!--
             如果想要在事件处理韩式自定义传参以后还想得到原来的事件本身参数则手动指定$event  => 原来的事件本身参数

             在组件上使用v-model 当你给子组件提供数据既要使用又要修改 使用v-model简化数据绑定
             v-model="article.cover.images[index]"
             :value
             @input 默认监听  当事件发生它会让 绑定数据=事件参数
          -->
           <upload-cover v-for='(item,index) in article.cover.type' :key="item" v-model="article.cover.images[index]"/>

           <!--<upload-cover v-for='(item,index) in article.cover.type' :key="item" @update-cover="onUpdateCover(index,$event)" :show-image="article.cover.images[index]"/>-->
          </template>
        </el-form-item>
        <el-form-item label="频道" prop="channel_id">
          <el-select v-model="article.channel_id" placeholder="请选择频道">
            <el-option v-for="(item,index) in ChannelsList" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <!--el-button 有默认参数-->
          <el-button type="primary" @click="onPublish(false)">{{$route.query.id ? '修改':'发布'}}</el-button>
          <el-button @click="onPublish(true)" v-show="!$route.query.id">存入草稿</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getChannels, addArticle, currentArticle, updateArticle } from '@/api/article.js'
import {
  // 需要的 extensions
  ElementTiptap,
  Doc,
  Text,
  Paragraph,
  Heading,
  Bold,
  Underline,
  Italic,
  Strike,
  ListItem,
  BulletList,
  OrderedList,
  Image,
  Fullscreen,
  Preview,
  TextColor
} from 'element-tiptap'
import 'element-tiptap/lib/index.css'
import { updataImage } from '@/api/image.js'
import uploadCover from './components/upload-cover.vue'
export default {
  name: 'publishIndex',
  components: {
    'el-tiptap': ElementTiptap,
    uploadCover
  },
  props: {},
  data () {
    var isContent = (rule, value, callback) => {
      if (value === '<p></p>') {
        return callback(new Error('请输入文章内容'))
      } else {
        // 验证通过
        callback()
      }
    }
    return {
      article: {
        title: '',
        content: '',
        cover: { // 文章封面
          type: 1,
          images: []
        },
        channel_id: null
      },
      ChannelsList: [], // 频道列表
      extensions: [
        new Doc(),
        new Text(),
        new Paragraph(),
        new Heading({ level: 5 }),
        new Bold({ bubble: true }), // 在气泡菜单中渲染菜单按钮
        new Underline({ bubble: true, menubar: false }), // 在气泡菜单而不在菜单栏中渲染菜单按钮
        new Italic(),
        new Strike(),
        new ListItem(),
        new BulletList(),
        new OrderedList(),
        new Image({
          // 上传用户图片素材
          // 如果接口要求conteny-type是multipart/form-data ，则请求体必须使用FormData
          uploadRequest (file) {
            const fd = new FormData()
            fd.append('image', file)
            console.log(fd)
            return updataImage(fd).then(res => {
              return res.data.data.url
            })
          }
        }),
        new Fullscreen(),
        new Preview(),
        new TextColor()
      ],
      formRules: {
        title: [
          {
            required: true, message: '请输入文章标题', trigger: 'blur'
          },
          {
            min: 5, max: 30, message: '长度为5-30个字符', trigger: 'blur'
          }
        ],
        content: [
          { required: true, validator: isContent, trigger: 'blur' },
          { required: true, message: '请输入文章内容', trigger: 'blur' }

        ],
        channel_id: [
          { required: true, message: '请选择文章频道' }
        ]
      }
    }
  },
  computed: {},
  watch: {},
  created () {
    this.getChannels()
    // 由于我们让发布和修改使用的同一个组件，哲理要判断一下，如果请求路径中有id则请求展示文章内容
    if (this.$route.query.id) {
      this.loadArticle()
    }
  },
  mounted () {},
  methods: {
    onSubmit () {
      console.log('submit!')
    },
    getChannels () {
      getChannels().then(res => {
        const { channels } = res.data.data
        // console.log(channels)
        this.ChannelsList = channels
      })
    },
    onPublish (draft = false) {
      // 验证
      this.$refs['publish-form'].validate((valid) => {
        console.log(valid)
        if (!valid) {
          // 如果验证失败
          return false
        } else {
          // 验证通过
          // 如果是修改文章执行修改操作 否则是添加操作
          const id = this.$route.query.id
          if (id) {
            // 修改操作
            updateArticle(id, this.article, draft).then(res => {
              console.log(res)
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              // 跳转到内容管理页面
              this.$router.push('/article')
            })
          } else {
            addArticle(this.article, draft).then(res => {
              // console.log(res)
              this.$message({
                message: `${draft ? '存入草稿' : '发布'}成功`,
                type: 'success'
              })
              // 跳转到内容管理页面
              this.$router.push('/article')
            })
          }
        }
      })
    },
    // 修改文章内容
    loadArticle () {
      currentArticle(this.$route.query.id).then(res => {
        this.article = res.data.data
      })
    },
    onUpdateCover (index, url) {
      console.log(url)
      this.article.cover.images[index] = url
    }
  }
}
</script>

<style scoped lang="less">
 .filter-card{
    margin-top:10px;
 }
 .filter-content{
    margin-top:20px;
 }
</style>
